﻿using RXY_Mall.Application.Manager.Dto;
using RXY_Mall.Core;
using RXY_Mall.Core.Tool;
using RXY_Mall.Domain;
using System;
using System.Linq;
using System.Text;
using System.Data.Entity;
using System.Threading.Tasks;

namespace RXY_Mall.Application.Manager
{
    public class ManagerService : RXY_MallAppServiceBase, IManagerService
    {
        public Response<AccountSessionDto> AdminLogin(string userName, string password)
        {
            LogHelper.WriteLog("总后台登录方法被调用：UserName={" + userName + "}");
            StringBuilder errorList = new StringBuilder();
            userName = userName.TrimEnd().TrimStart();
            //用户名不能为空
            if (string.IsNullOrWhiteSpace(userName))
            {
                errorList.Append("用户名不能为空；");
            }
            //密码不能为空
            if (string.IsNullOrWhiteSpace(password))
            {
                errorList.Append("密码不能为空；");
            }

            if (!string.IsNullOrWhiteSpace(errorList.ToString()))
            {
                return ReturnError<AccountSessionDto>(errorList.ToString());
            }

            var user = db.gw_managers
                        .Where(i => i.role_type == 3 && i.user_name == userName && i.status == 1).FirstOrDefault();
            if (null != user)
            {
                if (SecureHelper.Get32Md5Str(password + user.solt, true) == user.password)
                {
                    if (string.IsNullOrEmpty(user.solt))
                    {
                        user.solt = RandomHelper.CreateRandomValue(6);
                        user.password = SecureHelper.Get32Md5Str(password + user.solt, true);
                        db.SaveChanges();
                    }
                    string token = Guid.NewGuid().ToString();
                    return ReturnSuccess<AccountSessionDto>(new AccountSessionDto() { Id = user.id, UserName = user.user_name, Token = token });
                }
                else
                {
                    return ReturnError<AccountSessionDto>("密码错误!");
                }
            }
            else
            {
                return ReturnError<AccountSessionDto>("账号或密码输入有误!");
            }
        }

        public AccountSessionDto GetUserDetailsById(int id)
        {
            var user = db.gw_managers.FirstOrDefault(i => i.id == id && i.status == 0);
            return new AccountSessionDto() { Id = user.id, UserName = user.user_name };
        }

        public Response<bool> UpdatePassword(int managerId, string oldPassword, string newPassword)
        {
            var user = db.gw_managers.FirstOrDefault(i => i.id == managerId);
            if (null != user)
            {
                //验证老密码
                if (SecureHelper.Get32Md5Str(oldPassword + user.solt, true) != user.password)
                {
                    return ReturnError<bool>("原密码错误");
                }
                else
                {
                    var userList = db.gw_managers.Where(i => i.role_type == 2 && i.user_name == user.user_name && i.status == 0).ToList();
                    if (userList.Count() > 1)
                    {
                        var exit = userList.Where(i => i.password == SecureHelper.Get32Md5Str(newPassword + i.solt, true) && i.id != managerId);
                        if (exit.Count() > 0)
                        {
                            return ReturnError<bool>("相同用户名不能使用同一秘密");
                        }
                    }

                    user.password = SecureHelper.Get32Md5Str(newPassword + user.solt, true);
                    db.SaveChanges();
                    return ReturnSuccess<bool>(true);
                }
            }
            else
                return ReturnError<bool>("账户不存在");
        }

        public Response<bool> UpdatePayPassword(int managerId, int shopId, string oldPassword, string newPassword)
        {
            if (shopId > 0)
            {
                var model = db.gw_shop_passwords.FirstOrDefault(i => i.shop_id == shopId && i.type == 1);
                if (model == null)
                {
                    var entity = new gw_shop_password()
                    {
                        shop_id = shopId,
                        type = 1,
                        add_time = DateTime.Now,
                        solt = RandomHelper.CreateRandomValue(6),
                    };
                    entity.password = SecureHelper.Get32Md5Str("123456" + entity.solt, true);
                    model = db.gw_shop_passwords.Add(entity);
                    db.SaveChanges();
                }
                if (null != model)
                {
                    //验证老密码
                    if (SecureHelper.Get32Md5Str(oldPassword + model.solt, true) != model.password)
                    {
                        return ReturnError<bool>("原密码错误");
                    }
                    else
                    {
                        model.password = SecureHelper.Get32Md5Str(newPassword + model.solt, true);
                        db.SaveChanges();
                        return ReturnSuccess<bool>(true);
                    }
                }
                else
                {
                    return ReturnError<bool>("账号不存在");
                }
            }
            else
            {
                return ReturnError<bool>("店铺参数错误");
            }
        }

        public Response<AccountSessionDto> ShopAdminLogin(string userName, string password)
        {
            LogHelper.WriteLog("商家登录方法被调用：UserName={" + userName + "}");
            StringBuilder errorList = new StringBuilder();
            userName = userName.TrimEnd().TrimStart();
            //用户名不能为空
            if (string.IsNullOrWhiteSpace(userName))
            {
                errorList.Append("用户名不能为空；");
            }
            //密码不能为空
            if (string.IsNullOrWhiteSpace(password))
            {
                errorList.Append("密码不能为空；");
            }
            if (!string.IsNullOrWhiteSpace(errorList.ToString()))
            {
                return ReturnError<AccountSessionDto>(errorList.ToString());
            }
            //var user = db.gw_manager.Where(i =>i.role_type==2&& i.user_name == userName && i.is_lock == 0).FirstOrDefault();
            var user = db.gw_managers.Where(i => i.role_type == 2 && i.user_name == userName && i.status == 0);
            //var userlist = db.gw_manager.Where(i => i.role_type == 2  && i.is_lock == 0);
            //foreach (var item in userlist)
            //{
            //    if (item.shop_id ==null|| item.shop_id <= 0)
            //    {
            //        if (item.id==44)
            //        {
            //            item.shop_id = 200071;
            //            item.solt = "423445"+ item.shop_id;
            //            item.password = SecureHelper.Get32Md5Str("qj" + item.shop_id + item.solt, true);
            //        }
            //        if (item.id == 45)
            //        {
            //            item.shop_id = 200072;
            //            item.solt = "137347" + item.shop_id;
            //            item.password = SecureHelper.Get32Md5Str("qj" + item.shop_id + item.solt, true);
            //        }
            //        if (item.id == 46)
            //        {
            //            item.shop_id = 200073;
            //            item.solt = "760088" + item.shop_id;
            //            item.password = SecureHelper.Get32Md5Str("qj" + item.shop_id + item.solt, true);
            //        }
            //    }
            //}
            //db.SaveChanges();
            var manager = new gw_manager();
            if (null != user)
            {
                if (user.Count() == 1)
                {
                    manager = (user.ToList())[0];
                    if (SecureHelper.Get32Md5Str(password + manager.solt, true) != manager.password)
                    {
                        return ReturnError<AccountSessionDto>("密码错误!");
                    }
                    //if (string.IsNullOrEmpty(manager.solt))
                    //{
                    //manager.solt = RandomHelper.CreateRandomValue(6) + manager.shop_id;
                    //manager.password = SecureHelper.Get32Md5Str("qj" + manager.shop_id + manager.solt, true);
                    //db.SaveChanges();
                    //}
                }
                else
                {

                    foreach (var item in user)
                    {
                        if (SecureHelper.Get32Md5Str(password + item.solt, true) == item.password)
                        {
                            manager = item;
                            //manager.solt = RandomHelper.CreateRandomValue(6) + manager.shop_id;
                            //manager.password = SecureHelper.Get32Md5Str("qj"+ manager.shop_id + manager.solt, true);

                        }
                    }
                }
                //db.SaveChanges();
                if (manager.id == 0)
                {
                    return ReturnError<AccountSessionDto>("账号或密码输入有误!");
                }
                string token = Guid.NewGuid().ToString();
                var shop = db.gw_shops.FirstOrDefault(i => i.id == manager.shop_id && i.deleted == false && i.status == 1 && i.mangermobile == userName.Trim());
                if (shop == null)
                {
                    return ReturnError<AccountSessionDto>("账号被冻结！");
                }

                return ReturnSuccess<AccountSessionDto>(new AccountSessionDto() { Id = manager.id, ShopId = shop.id, UserName = manager.user_name, Token = token });
            }
            else
            {
                return ReturnError<AccountSessionDto>("账号被冻结或不存在!");
            }
        }

        public async Task<Response<bool>> AddManager(ManagerAddInput input)
        {
            throw new NotImplementedException();
        }

        public Response<IPagedList<ManagerListOutput>> GetManagersByPage(string start_date, string end_date, string manager_name, string manager_id, int status, int page_index = 1, int page_size = 10)
        {
            DateTime dtMin = DateTime.MinValue;
            DateTime dtMax = DateTime.MaxValue;
            Response<IPagedList<ManagerListOutput>> output = new Response<IPagedList<ManagerListOutput>>();
           
            try
            {
                var source = db.gw_managers
                .Include(m => m.gw_company)
                .Include(m => m.gw_shop)
                .Where(m => !m.deleted)
                .Select(m => new ManagerListOutput()
                {
                    add_time = m.add_time,
                    company_name = m.gw_company.name,
                    shop_name = m.gw_shop.name,

                    manager_id = m.id,                    
                    manager_name = m.user_name,
                    //manager_type =  m.role_type,
                    mobile = m.phone,
                    real_name = m.real_name,
                    status = m.status,
                });

                if (status > -1)
                {
                    source = source.Where(m => m.status == status);
                }

                if (!string.IsNullOrWhiteSpace(manager_name))
                {
                    source = source.Where(m => m.manager_name.Contains(manager_name));
                }
                if (!string.IsNullOrWhiteSpace(manager_id) && Validator.IsInt(manager_id))
                {
                    int user_no = int.Parse(manager_id);
                    source = source.Where(m => m.manager_id == user_no);
                }
                if (!string.IsNullOrWhiteSpace(start_date))
                {
                    dtMin = DateTime.Parse(start_date);
                }
                if (!string.IsNullOrWhiteSpace(end_date))
                {
                    dtMax = DateTime.Parse(end_date).Date.AddDays(1); ;
                }
                source = source.Where(m => m.add_time >= dtMin && m.add_time <= dtMax);
                source = source.OrderByDescending(s => s.add_time);

                var pagelist = new PagedList<ManagerListOutput>(source, page_index, page_size);
                output.code = 1;
                output.data = pagelist;
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
                output.code = 2;
                output.msg = ex.Message;
            }
            return output;
        }

        public bool SetManagerPwd(int memberId, int id, string v)
        {
            throw new NotImplementedException();
        }

        public bool SetIsUse(int manageId, int id, int isUse)
        {
            LogHelper.WriteLog(String.Format("管理员{0}操作用户{1}状态为{2}", manageId, id, isUse));
            var entity = db.gw_managers.Find(id);
            if (null != entity)
            {
                entity.status = (byte)isUse;
                db.Entry(entity).Property(u => u.status).IsModified = true;

                db.SaveChanges();
                return true;
            }
            return false;
        }
    }
}
